/**
 * @Description:登录主入口
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from "react";
import { actions } from "../../../../reducers/main";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import {
  message,
  Spin,
  Table,
  Button,
  Icon,
  Pagination,
  Modal,
  Tag,
  Dropdown,
  Menu,
  Input,
  Tooltip,
  Popover
} from "antd";
import MyForm from "../../../components/Form";
import axios from "../../../../apis/api";
import qs from "qs";
import Order from "./order";
import md5 from "md5-node";
import AddUserForm from "./addUserForm";
import { subtractMoney } from "../../../../utils/number";

const mapStateToProps = (state, ownProps) => {
  return {
    user: state.main.user,
    vwAgentCashStat: state.main.vwAgentCashStat,
    vwAgentCashDayStat: state.main.vwAgentCashDayStat,
    isAdmin: state.main.isAdmin
  };
};

const mapDispatchToProps = dispatch => {
  return {
    fetchInitData: next => dispatch(actions.fetchInitData(next))
  };
};

class BusinessSummary extends Component {
  state = {
    host: "",
    initForm: {
      userName: "",
      parentUserName: ""
    },
    formItmes: [],
    searchParam: {},
    loading: false,
    depMap: {},
    pageSize: 10,
    curPage: 1,
    tableData: {
      total: 0,
      rows: []
    },
    payTypes: [], // 支付类型
    payTypesMap: {},
    pauseOrderVisible: false,
    curSelData: {},
    scoreVisible: false,
    scoreValue: 0,
    resetVisible: false,
    resetValue: 0,
    initCardForm: {},
    visibleDlg: false,
    cardFormTitle: "",
    cardFormType: "add",
    payVisible: false,
    payValue: "",
    pwdVisible: false,
    pwdValue: ""
  };
  addUser = () => {
    this.setState({
      visibleDlg: true,
      initCardForm: {},
      cardFormType: "add",
      cardFormTitle: "添加"
    });
  };
  editUser = card => {
    this.setState({
      visibleDlg: true,
      cardFormType: "edit",
      initCardForm: card,
      cardFormTitle: "修改"
    });
  };
  handleSearch = value => {
    this.setState(
      {
        curPage: 1,
        searchParam: value
      },
      this.searchTable
    );
  };

  componentDidMount() {
    this.init();
    this.getSalesman();
    this.getHost();
  }

  getHost = async () => {
    const result = await axios.get("/channel/businessInfo/host/json");
    this.setState({ host: result.data.host });
  };

  getSalesman = async () => {
    const result = await axios.post("/system/user/salesman");
    const options = result.rows.map(item => {
      return {
        value: item.userId,
        label: item.userName
      };
    });
    const formItems = [
      {
        label: "业务员",
        key: "rootUserId",
        type: "select",
        options: [{ value: "", label: "所有" }, ...options]
      },
      {
        label: "用户类型",
        key: "orderPrice",
        type: "select",
        options: [
          { value: "", label: "所有" },
          { value: "100", label: "假人" },
          { value: "200", label: "真人" }
        ]
      },
      {
        label: "会员手机号",
        key: "userName",
        type: "input"
      },
      {
        label: "邀请吗",
        key: "invitationCode",
        type: "input"
      },
      {
        label: "创建开始时间",
        key: "params[beginTime]",
        type: "DatePicker"
      },
      {
        label: "创建结束时间",
        key: "params[endTime]",
        type: "DatePicker"
      }
    ];
    this.setState({ formItmes: formItems });
  };

  init = async () => {
    this.searchTable();
  };

  searchTable = async () => {
    const { pageSize, curPage, searchParam } = this.state;
    const query = {
      orderByColumn: "userId",
      isAsc: "desc",
      pageSize,
      pageNum: curPage,
      ...searchParam,
      "params[beginTime]":
        (searchParam.params &&
          searchParam.params.beginTime &&
          searchParam.params.beginTime.format("YYYY-MM-DD")) ||
        "",
      "params[endTime]":
        (searchParam.params &&
          searchParam.params.endTime &&
          searchParam.params.endTime.format("YYYY-MM-DD")) ||
        ""
    };
    try {
      this.setState({
        loading: true
      });
      const result = await axios.post(
        "/channel/vwBusinessCashStat/list",
        qs.stringify(query)
      );
      console.log(result);
      if (result.code === 0) {
        this.setState({
          tableData: result,
          loading: false
        });
      } else {
        this.setState({
          loading: false
        });
        message.error(result.msg);
      }
    } catch (e) {
      this.setState({
        loading: false
      });
      message.error(e.message);
    }
  };
  //翻页
  handlePageChange = (page, pageSize) => {
    this.setState(
      {
        curPage: page
      },
      this.searchTable
    );
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        curPage: current
      },
      this.searchTable
    );
  };

  getMoreBtns = user => {
    return (
      <Menu>
        {/*<Menu.Item>*/}
        {/*  <Button type={"dashed"} onClick={() => this.editUser(user)}>*/}
        {/*    编辑会员*/}
        {/*  </Button>*/}
        {/*</Menu.Item>*/}
        <Menu.Item>
          <Button
            type={"dashed"}
            onClick={() =>
              Modal.confirm({
                title: "系统提示",
                content: `确定更新用户【${user.userName}】的系统钱包吗？`,
                okText: "确定",
                cancelText: "取消",
                onOk: async () => {
                  await axios.post(
                    "/channel/businessInfo/updateAddress",
                    qs.stringify({
                      userId: user.userId
                    })
                  );
                  message.success("更新成功");
                  this.init();
                }
              })
            }
          >
            更新系统钱包
          </Button>
        </Menu.Item>
        <Menu.Item>
          <Button
            type={"dashed"}
            onClick={() =>
              this.setState({ payVisible: true, curSelData: user })
            }
          >
            支付密码
          </Button>
        </Menu.Item>
        <Menu.Item>
          <Button
            type={"dashed"}
            onClick={() =>
              this.setState({ pwdVisible: true, curSelData: user })
            }
          >
            重置密码
          </Button>
        </Menu.Item>
        <Menu.Item>
          <Button
            type={"dashed"}
            onClick={() =>
              // 删除用户
              Modal.confirm({
                title: "系统提示",
                content: "确定删除该条用户信息吗？",
                okText: "确定",
                cancelText: "取消",
                onOk: async () => {
                  await axios.post(
                    "/system/user/remove",
                    qs.stringify({
                      ids: user.userId
                    })
                  );
                  message.success("删除成功");
                  this.init();
                }
              })
            }
          >
            删除
          </Button>
        </Menu.Item>
      </Menu>
    );
  };

  addScore = async () => {
    const { scoreValue } = this.state;
    if (scoreValue === 0) {
      message.info("请输入非0的数字！");
      return;
    }
    this.setState({ loading: true });
    try {
      const result = await axios.post(
        "/channel/channelOrder/addOrder",
        qs.stringify({
          userId: this.state.curSelData.userId,
          amount: this.state.scoreValue,
          type: "手动上分"
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ scoreVisible: false, loading: false });
    this.init();
  };

  reset = async () => {
    const { resetValue } = this.state;
    try {
      const result = await axios.post(
        "/channel/businessInfoOrder/edit",
        qs.stringify({
          userId: this.state.curSelData.userId,
          daySum: resetValue
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ resetVisible: false });
    this.init();
  };

  updateAddress = async () => {
    const { addressValue } = this.state;
    try {
      const result = await axios.post(
        "/channel/bankInfo/updateSelf",
        qs.stringify({
          userId: this.state.curSelData.userId,
          bankNo: addressValue
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ addressVisible: false });
    this.init();
  };

  updatePayPwd = async () => {
    const { payValue } = this.state;
    try {
      const result = await axios.post(
        "/channel/businessInfo/resetPayPwd",
        qs.stringify({
          id: this.state.curSelData.userId,
          password: md5(payValue)
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ payVisible: false });
    this.init();
  };

  updateUserPwd = async () => {
    const { pwdValue } = this.state;
    try {
      const result = await axios.post(
        "/system/user/resetPwd",
        qs.stringify({
          userId: this.state.curSelData.userId,
          password: md5(pwdValue)
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ pwdVisible: false });
    this.init();
  };

  columns = [
    {
      title: "用户类型",
      dataIndex: "orderPrice",
      key: "orderPrice",
      render: text => {
        return text === 100 ? (
          <Tag color="#f50">假人</Tag>
        ) : (
          <Tag color="#108ee9">真人</Tag>
        );
      }
    },
    {
      title: "会员编号",
      dataIndex: "userId",
      key: "userId"
    },
    {
      title: "邀请码",
      dataIndex: "invitationCode",
      key: "invitationCode"
    },
    {
      title: "会员手机号",
      dataIndex: "userName",
      key: "userName"
    },
    {
      title: "当前抢单数",
      dataIndex: "daySum",
      key: "daySum"
    },
    {
      title: "业务员",
      dataIndex: "rootUserName",
      key: "rootUserName"
    },
    {
      title: "直接上级",
      dataIndex: "parentUserName",
      key: "parentUserName"
    },
    {
      title: "可用金额",
      dataIndex: "finalCash",
      key: "finalCash",
      render: (text, record) => {
        return subtractMoney(text, record.pauseOrderPrice || 0);
      }
    },
    {
      title: "总金额",
      dataIndex: "amountSum",
      key: "amountSum"
    },
    {
      title: "入金金额",
      dataIndex: "paySum",
      key: "paySum"
    },
    {
      title: "出金中金额",
      dataIndex: "frzzingCash",
      key: "frzzingCash"
    },
    {
      title: "出金金额",
      dataIndex: "hasCashSum",
      key: "hasCashSum"
    },
    {
      title: "最后登录时间",
      dataIndex: "loginDate",
      key: "loginDate"
    },
    {
      title: "当前抢单佣金",
      dataIndex: "batchTaskIncomeCash",
      key: "batchTaskIncomeCash"
    },
    {
      title: "总佣金",
      dataIndex: "incomeCash",
      key: "incomeCash"
    },
    {
      title: "一级代理数",
      dataIndex: "firstSum",
      key: "firstSum"
    },
    {
      title: "系统钱包地址",
      dataIndex: "systemWalletAddress",
      key: "systemWalletAddress"
    },
    {
      title: "用户钱包地址",
      dataIndex: "userWalletAddress",
      key: "userWalletAddress"
    },
    {
      title: "今日抢单数",
      dataIndex: "todayTaskIncomeCout",
      key: "todayTaskIncomeCout"
    },
    {
      title: "注册时间",
      dataIndex: "createTime",
      key: "createTime"
    },
    {
      title: "操作",
      dataIndex: "op",
      key: "op",
      fixed: "right",
      render: (_, row) => {
        return (
          <div style={{ display: "flex", alignItems: "center" }}>
            <Button
              type="link"
              onClick={() => {
                this.setState({ curSelData: row, pauseOrderVisible: true });
              }}
            >
              卡单
            </Button>
            {(row.orderPrice === 100 || this.props.isAdmin) && (
              <Button
                type="link"
                onClick={() => {
                  this.setState({ curSelData: row, scoreVisible: true });
                }}
              >
                上分
              </Button>
            )}
            <Button
              type="link"
              onClick={() => {
                this.setState({ curSelData: row, resetVisible: true });
              }}
            >
              重置单数
            </Button>
            <Button
              type="link"
              onClick={() => {
                this.setState({ curSelData: row, addressVisible: true });
              }}
            >
              收款地址
            </Button>
            <Dropdown overlay={this.getMoreBtns(row)} placement="bottomLeft">
              <Icon
                type="ellipsis"
                style={{ color: "#1890ff", cursor: "pointer" }}
              />
            </Dropdown>
          </div>
        );
      }
    }
  ];

  getContent = () => {
    const { host } = this.state;
    const text = host + "/" + this.props.user.remark;
    return (
      <div>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between"
          }}
        >
          <span>邀请码：{this.props.user.remark}</span>
          <Button
            type={"link"}
            onClick={() => {
              navigator.clipboard
                .writeText(this.props.user.remark)
                .then(function() {
                  message.success("已复制");
                })
                .catch(function(error) {
                  console.error("复制失败:", error);
                });
            }}
          >
            复制
          </Button>
        </div>
        <div style={{ display: "flex", alignItems: "center" }}>
          <span>邀请链接：{text}</span>
          <Button
            type={"link"}
            onClick={() => {
              navigator.clipboard
                .writeText(text)
                .then(function() {
                  message.success("已复制");
                })
                .catch(function(error) {
                  console.error("复制失败:", error);
                });
            }}
          >
            复制
          </Button>
        </div>
      </div>
    );
  };

  render() {
    const {
      initForm,
      formItmes,
      loading,
      tableData,
      curPage,
      pageSize,
      host
    } = this.state;
    const text = host + "/" + this.props.user.remark;
    return (
      <div>
        <MyForm
          initForm={initForm}
          items={formItmes}
          handleSearch={this.handleSearch}
        />
        <Spin spinning={loading}>
          <div style={{ marginBottom: 10 }}>
            <Button type="primary" onClick={this.addUser}>
              添加会员
            </Button>
            <Popover content={this.getContent()} title="Title" trigger="hover">
              <Button
                icon="file-text"
                type="link"
                // onClick={() => {
                //   navigator.clipboard
                //     .writeText(text)
                //     .then(function() {
                //       message.success("已复制");
                //     })
                //     .catch(function(error) {
                //       console.error("复制失败:", error);
                //     });
                // }}
              >
                {this.props.user.remark}
              </Button>
            </Popover>
          </div>
          <Table
            dataSource={tableData.rows}
            columns={this.columns}
            pagination={false}
            scroll={{ x: true }}
          />
          <Pagination
            style={{ marginTop: 10, marginBottom: 20 }}
            total={tableData.total}
            showTotal={total => `共 ${total} 项`}
            pageSizeOptions={["10", "20", "50", "100", "500"]}
            showSizeChanger
            onShowSizeChange={this.onShowSizeChange}
            pageSize={pageSize}
            current={curPage}
            onChange={this.handlePageChange}
          />
        </Spin>
        <Order
          onClose={() => this.setState({ pauseOrderVisible: false })}
          visible={this.state.pauseOrderVisible}
          data={this.state.curSelData}
        />
        <Modal
          title="上分"
          visible={this.state.scoreVisible}
          confirmLoading={this.state.loading}
          onOk={this.addScore}
          onCancel={() => this.setState({ scoreVisible: false })}
        >
          <div style={{ display: "flex", alignItems: "center" }}>
            <div>请输入金额为：</div>
            <Input
              type={"number"}
              style={{ width: 200 }}
              value={this.state.scoreValue}
              onChange={value =>
                this.setState({ scoreValue: value.target.value })
              }
            />
          </div>
        </Modal>
        <Modal
          title="重置单数"
          visible={this.state.resetVisible}
          confirmLoading={this.state.loading}
          onOk={this.reset}
          onCancel={() => this.setState({ resetVisible: false })}
        >
          <div style={{ display: "flex", alignItems: "center" }}>
            <div>请输入当前已刷单数为：</div>
            <Input
              type={"number"}
              style={{ width: 200 }}
              value={this.state.resetValue}
              onChange={value =>
                this.setState({ resetValue: value.target.value })
              }
            />
          </div>
        </Modal>
        <Modal
          title="更新收款地址"
          visible={this.state.addressVisible}
          onOk={this.updateAddress}
          onCancel={() => this.setState({ addressVisible: false })}
        >
          <div style={{ display: "flex", alignItems: "center" }}>
            <div>请输入收款地址为：</div>
            <Input
              style={{ width: 200 }}
              value={this.state.addressValue}
              onChange={value =>
                this.setState({ addressValue: value.target.value })
              }
            />
          </div>
        </Modal>
        <Modal
          title="重置支付密码"
          visible={this.state.payVisible}
          onOk={this.updatePayPwd}
          onCancel={() => this.setState({ payVisible: false })}
        >
          <div style={{ display: "flex", alignItems: "center" }}>
            <div>请输入支付密码：</div>
            <Input
              style={{ width: 200 }}
              value={this.state.payValue}
              onChange={value =>
                this.setState({ payValue: value.target.value })
              }
            />
          </div>
        </Modal>
        <Modal
          title="重置登录密码"
          visible={this.state.pwdVisible}
          onOk={this.updateUserPwd}
          onCancel={() => this.setState({ pwdVisible: false })}
        >
          <div style={{ display: "flex", alignItems: "center" }}>
            <div>请输入登录密码：</div>
            <Input
              style={{ width: 200 }}
              value={this.state.pwdValue}
              onChange={value =>
                this.setState({ pwdValue: value.target.value })
              }
            />
          </div>
        </Modal>
        <AddUserForm
          visible={this.state.visibleDlg}
          initForm={this.state.initCardForm}
          title={this.state.cardFormTitle}
          cardFormType={this.state.cardFormType}
          okCb={() => {
            this.setState({ visibleDlg: false });
            this.init();
          }}
          cancelCb={() => this.setState({ visibleDlg: false })}
        />
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(BusinessSummary));
